package mSocket.mNetty;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;

/**
* @author jie
* @version 创建时间：2018年8月15日 下午3:55:21
*   阻塞I/O
链接：https://www.jianshu.com/p/b9f3f6a16911

*/
public class PlainOioServer {
	public static void main(String[] args) {
		PlainOioServer plainOioServer = new PlainOioServer();
		try {
			plainOioServer.serve(10899);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public void serve(int port) throws IOException {
		final ServerSocket socket = new ServerSocket(port); // 1
		try {
			for (;;) {
				final Socket clientSocket = socket.accept(); // 2
				System.out.println("Accepted connection from " + clientSocket);

				new Thread(new Runnable() { // 3
					@Override
					public void run() {
						OutputStream out;
							InputStream is = null;
							InputStreamReader isr = null;
							BufferedReader br = null;
							OutputStream os = null;
							PrintWriter pw = null;
							try {
								// socket获取字节输入流
								is = clientSocket.getInputStream();
								// 将字节输入流转字符输入流
								isr = new InputStreamReader(is);
								// 将字符输入流转行输入流
								br = new BufferedReader(isr); //
								String message = null;
								while ((message = br.readLine()) != null) {
									System.out.println("客户端发来消息：" + message);
								}

							out = clientSocket.getOutputStream();
							out.write("Hi!\r\n".getBytes(Charset.forName("UTF-8"))); // 4
							out.flush();
							clientSocket.close(); // 5

						} catch (IOException e) {
							e.printStackTrace();
							try {
								clientSocket.close();
							} catch (IOException ex) {
								// ignore on close
							}
						}
					}
				}).start(); // 6
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
